import { Router } from "express";
import { authenticateToken } from "../middleware/auth";
import { DrugInfo, IDrugInfo } from "../models/mongodb-schemas";

const router = Router();

// GET /v1/drug/search - 搜索药品
router.get("/search", async (req, res) => {
  try {
    const { 
      q, 
      category, 
      page = 1, 
      limit = 20,
      sortBy = 'name',
      sortOrder = 'asc',
      priceMin,
      priceMax,
      inStock
    } = req.query;

    // 构建查询条件
    const filter: any = {};
    
    // 文本搜索
    if (q) {
      filter.$text = { $search: q as string };
    }
    
    // 分类过滤
    if (category) {
      filter.category = category;
    }
    
    // 价格范围过滤
    if (priceMin || priceMax) {
      filter.price = {};
      if (priceMin) filter.price.$gte = parseFloat(priceMin as string);
      if (priceMax) filter.price.$lte = parseFloat(priceMax as string);
    }
    
    // 库存过滤
    if (inStock === 'true') {
      filter.inStock = true;
    }

    // 排序
    const sort: any = {};
    sort[sortBy as string] = sortOrder === 'desc' ? -1 : 1;

    // 分页
    const pageNum = parseInt(page as string);
    const limitNum = parseInt(limit as string);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const [drugs, total] = await Promise.all([
      DrugInfo.find(filter)
        .sort(sort)
        .skip(skip)
        .limit(limitNum)
        .lean(),
      DrugInfo.countDocuments(filter)
    ]);

    res.json({
      success: true,
      data: {
        drugs,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      }
    });

  } catch (error) {
    console.error('搜索药品失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索药品失败',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

// GET /v1/drug/categories - 获取药品分类统计
router.get("/categories", async (req, res) => {
  try {
    const categories = await DrugInfo.aggregate([
      {
        $group: {
          _id: "$category",
          count: { $sum: 1 },
          avgPrice: { $avg: "$price" }
        }
      },
      {
        $sort: { count: -1 }
      }
    ]);

    const categoryMap = {
      'antibiotics': '抗生素',
      'analgesics': '止痛药',
      'cold': '感冒药',
      'digestive': '消化科',
      'cardiovascular': '心血管',
      'respiratory': '呼吸系统',
      'other': '其他'
    };

    const result = categories.map(cat => ({
      id: cat._id,
      name: categoryMap[cat._id as keyof typeof categoryMap] || cat._id,
      count: cat.count,
      avgPrice: Math.round(cat.avgPrice * 100) / 100
    }));

    res.json({
      success: true,
      data: result
    });

  } catch (error) {
    console.error('获取药品分类失败:', error);
    res.status(500).json({
      success: false,
      message: '获取药品分类失败'
    });
  }
});

// GET /v1/drug/:id - 获取药品详情
router.get("/:id", async (req, res) => {
  try {
    const drugId = req.params.id;
    const drug = await DrugInfo.findOne({ drugId }).lean();
    
    if (!drug) {
      return res.status(404).json({
        success: false,
        message: '药品不存在'
      });
    }

    res.json({
      success: true,
      data: drug
    });

  } catch (error) {
    console.error('获取药品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取药品详情失败'
    });
  }
});

// POST /v1/drug - 创建药品信息 (需要管理员权限)
router.post("/", authenticateToken, async (req, res) => {
  try {
    const drugData = {
      drugId: `drug_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      ...req.body
    };

    const drug = new DrugInfo(drugData);
    await drug.save();

    res.status(201).json({
      success: true,
      data: drug,
      message: '药品创建成功'
    });

  } catch (error) {
    console.error('创建药品失败:', error);
    res.status(500).json({
      success: false,
      message: '创建药品失败',
      error: error instanceof Error ? error.message : '未知错误'
    });
  }
});

// PUT /v1/drug/:id - 更新药品信息 (需要管理员权限)
router.put("/:id", authenticateToken, async (req, res) => {
  try {
    const drugId = req.params.id;
    const updateData = {
      ...req.body,
      updatedAt: new Date()
    };

    const drug = await DrugInfo.findOneAndUpdate(
      { drugId },
      updateData,
      { new: true, runValidators: true }
    );

    if (!drug) {
      return res.status(404).json({
        success: false,
        message: '药品不存在'
      });
    }

    res.json({
      success: true,
      data: drug,
      message: '药品更新成功'
    });

  } catch (error) {
    console.error('更新药品失败:', error);
    res.status(500).json({
      success: false,
      message: '更新药品失败'
    });
  }
});

// DELETE /v1/drug/:id - 删除药品信息 (需要管理员权限)
router.delete("/:id", authenticateToken, async (req, res) => {
  try {
    const drugId = req.params.id;
    const drug = await DrugInfo.findOneAndDelete({ drugId });

    if (!drug) {
      return res.status(404).json({
        success: false,
        message: '药品不存在'
      });
    }

    res.json({
      success: true,
      message: '药品删除成功'
    });

  } catch (error) {
    console.error('删除药品失败:', error);
    res.status(500).json({
      success: false,
      message: '删除药品失败'
    });
  }
});

// GET /v1/drug/featured/popular - 获取热门药品
router.get("/featured/popular", async (req, res) => {
  try {
    const limit = parseInt(req.query.limit as string) || 10;
    
    const popularDrugs = await DrugInfo.find({ inStock: true })
      .sort({ reviewCount: -1, rating: -1 })
      .limit(limit)
      .lean();

    res.json({
      success: true,
      data: popularDrugs
    });

  } catch (error) {
    console.error('获取热门药品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门药品失败'
    });
  }
});

export default router;